/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.ResultCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/11 13:59
 * 控制文章封面的上传
 */
@Controller
public class ImagesUpload {
    CqLogger logger = CqLogger.getInstance();

    @Value("${prop.upload-folder}")
    private String UPLOAD_FOLDER;

    @PostMapping("api/upload")
    public ResponseEntity<Map<String, Object>> imagesUpload(@RequestParam(name = "file", required = false) MultipartFile file){
        Map<String, Object> resultMap = new HashMap<>();
        logger.print("调用上传图片接口");
        // 为空
        if(file.isEmpty()){
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_GET_INFORMATION);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_GET_INFORMATION);
            return ResponseEntity.ok(resultMap);
        }
        else if(!file.isEmpty()){
            String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1, file.getOriginalFilename().length());
            if (!"jpg,jpeg,png".toUpperCase().contains(suffix.toUpperCase())) {
                resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_FORMATTING_ERROR);
                resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_FORMATTING_ERROR);
                return ResponseEntity.ok(resultMap);
            }

            try{
                // 获取文件保存到文件夹
                String savePath = UPLOAD_FOLDER;
                // 如果目录不存在，则创建目录
                File saveDir = new File(savePath);
                if (!saveDir.exists()) {
                    saveDir.mkdirs();
                }

                //通过UUID生成唯一文件名
                String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;

                file.transferTo(new File(savePath + filename));

                String fileUrl = ResultCode.IMAGE_URL + filename;

                resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);
                resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);
                resultMap.put(ResultCode.url, fileUrl);
                return ResponseEntity.ok(resultMap);
            }catch (IOException e) {
                // 发生异常时返回包含错误信息的 JSON 对象
                resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_UPLOAD_ERROR);
                resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_UPLOAD_ERROR + e.getMessage());
                return ResponseEntity.ok(resultMap);
            }
        }
        return ResponseEntity.ok(resultMap);
    }
}
